package com.bnlr.lrparking.appui.order;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bumptech.glide.Glide;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.appui.order.stages.ByStagesDetailsActivity;
import com.bnlr.lrparking.appui.stall.StallDealDetailActivity;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.event.ApplyStategesEvent;
import com.bnlr.lrparking.model.BaseArrayBean;
import com.bnlr.lrparking.model.OrderDetailBean;
import com.bnlr.lrparking.appui.order.mode.OrderIntentBean;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.lrparking.widget.SuperTextView;
import com.bnlr.lrparking.widget.photo.PhotoViewerActivity;
import com.bnlr.lrparking.widget.photo.PhotoViewerBean;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 订单详情
 */
public class OrderDetailActivity extends BaseActivity {
    private Unbinder unbinder;
    @BindView(R.id.tv_nav_title)
    TextView tvTitle;
    @BindView(R.id.tv_order_pic)
    ImageView orderDetailPic;
    @BindView(R.id.stv_order_who)
    SuperTextView stvWho;
    @BindView(R.id.tv_order_title)
    TextView tvOrderTitle;
    @BindView(R.id.tv_order_number)
    TextView tvCarNumber;
    @BindView(R.id.tv_order_price)
    TextView tvOrderPrice;

    @BindView(R.id.order_detail_order_number)
    TextView tvOrderNumber;
    @BindView(R.id.order_detail_order_type)
    TextView tvOrderType;
    @BindView(R.id.order_detail_order_status)
    TextView tvOrderStatus;
    @BindView(R.id.order_detail_order_close)
    LinearLayout llClose;
    @BindView(R.id.order_detail_order_cause)
    TextView tvOrderCause;
    @BindView(R.id.order_detail_order_house)
    TextView tvOrderHouse;
    @BindView(R.id.order_detail_car_number)
    TextView tvOrderCarNumber;
    @BindView(R.id.order_detail_order_money)
    TextView tvOrderMoney;

    @BindView(R.id.order_detail_order_discount)
    TextView tvOrderDiscount;
    @BindView(R.id.order_detail_order_upper)
    TextView tvOrderUpper;
    @BindView(R.id.order_detail_place_date)
    TextView tvOrderPlaceDate;
    @BindView(R.id.order_detail_buy_date)
    TextView tvOrderBuyDate;
    @BindView(R.id.order_detail_salesman)
    TextView tvOrderSalesman;
    @BindView(R.id.order_detail_buy_man)
    TextView tvOrderBuyMan;
    @BindView(R.id.order_detail_final_date)
    TextView tvFinalDate;
    @BindView(R.id.stv_order_delete)
    SuperTextView stvDelete;
    @BindView(R.id.stv_order_see_ht)
    SuperTextView stvHeTong;
    @BindView(R.id.stv_order_call)
    SuperTextView stvCall;
    @BindView(R.id.stv_order_pay)
    SuperTextView stvPay;
    @BindView(R.id.stv_order_stages)
    SuperTextView stvStages;
    @BindView(R.id.ll_order_detail)
    LinearLayout llTop;
    @BindView(R.id.order_detail_address)
    TextView address;
    @BindView(R.id.ll_pay_time)
    LinearLayout llPayTime;
    @BindView(R.id.ll_pay_wk_time)
    LinearLayout llPayWkTIme;
    @BindView(R.id.tv_pay_tag)
    TextView tvPayTag;
    private OrderDetailBean.DataBean dataBean;
    private String orderId;
    private OrderIntentBean orderIntentBean = new OrderIntentBean();
    private List<String> photolist  = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        EventBus.getDefault().register(this);
        unbinder = ButterKnife.bind(this);
        tvTitle.setText("订单详情");
        Intent intent = getIntent();
        orderId = intent.getStringExtra("order_detail_id");

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void applyStages (ApplyStategesEvent event) {
        stvStages.setText("分期进度");
        dataBean.setIsByStage(1);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getOrderDetail(orderId);
    }

    /**
     * 删除订单
     * @param id
     */
    private void deleteOrder(String id) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.ORDER, LrConstant.POST);
            mRequest.add("action", "SetOrderStatus");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("orderId", id);
            mRequest.add("status",4);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomHttpListener<BaseArrayBean>(this, true, BaseArrayBean.class) {
                        @Override
                        public void doWork(BaseArrayBean data, String code) {
                            if (TextUtils.equals("1", code)) {
                                finish();
                            } else {
                                ToastUtils.showShort(data.getMsg()+"");
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                        }
                    }, true);
        } catch (Exception e) {
        }
    }
    /**
     * 获取订单详情
     * @param id
     */
    private void getOrderDetail(String id) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.ORDER, LrConstant.POST);
            mRequest.add("action", "GetUserOrderDetails");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("orderNumber", id);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomHttpListener<OrderDetailBean>(this, true, OrderDetailBean.class) {
                        @Override
                        public void doWork(OrderDetailBean data, String code) {
                            if (TextUtils.equals("1", code)) {
                                dataBean = data.getData();
                                setValue();
                            } else {
                                ToastUtils.showShort(data.getMsg()+"");
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                        }
                    }, true);
        } catch (Exception e) {
        }
    }

    private void setValue() {
        if (dataBean != null) {
            Glide.with(this).load(dataBean.getPhotoUrl())
                    .placeholder(R.mipmap.tab2_defaultgraph)
                    .error(R.mipmap.tab2_defaultgraph).into(orderDetailPic);
            if (dataBean.getSpaceOwerType() == 1) {
                stvWho.setText("开发商");
            } else {
                stvWho.setText("个人");
            }
            tvOrderTitle.setText(dataBean.getTitle());
            tvCarNumber.setText(dataBean.getNumber());
            address.setText(dataBean.getAddress());
            tvOrderPrice.setText(dataBean.getAdvanceMoneyStr());
            tvOrderNumber.setText(dataBean.getOrderNumber());
            tvOrderType.setText("车位保留金订单");
            tvOrderStatus.setText(dataBean.getStatus());
            if (dataBean.getStatusInt() == 5 || dataBean.getStatusInt() == 7 ) {
                tvOrderCause.setText(TextUtils.isEmpty(dataBean.getFailReason())?"无":dataBean.getFailReason());
            } else  {
                llClose.setVisibility(View.GONE);
            }
            tvOrderHouse.setText(dataBean.getName());
            tvOrderCarNumber.setText(dataBean.getNumber());
            tvOrderMoney.setText("¥"+dataBean.getAdvanceMoney());
            tvOrderDiscount.setText(dataBean.getDiscount());
            tvOrderUpper.setText(dataBean.getChineseMoney()+"元整");
            tvOrderPlaceDate.setText(TextUtils.isEmpty(dataBean.getCreateTime())?"未下单":dataBean.getCreateTime());
            tvOrderBuyDate.setText(TextUtils.isEmpty(dataBean.getHoldBeginTime())?"未付款":dataBean.getHoldBeginTime());
            tvFinalDate.setText(TextUtils.isEmpty(dataBean.getEndTime())?"还未付定金":dataBean.getEndTime());
            tvOrderSalesman.setText(TextUtils.isEmpty(dataBean.getDealUserName())?"无":dataBean.getDealUserName() + "  "+dataBean.getDealPhone());
            tvOrderBuyMan.setText(dataBean.getPayUserName() +"  " +dataBean.getPayUserPhone());
            if (dataBean.getIsByStage() == 0) {
                // 为分期
                stvStages.setText("申请分期");
            } else {
                // 已分期
                stvStages.setText("分期进度");
            }
            if (dataBean.getStatusInt() == 2 || dataBean.getStatusInt() == 3 || dataBean.getStatusInt() == 5
                    || dataBean.getStatusInt() == 6 || dataBean.getStatusInt() == 7 ) {
                stvStages.setVisibility(View.GONE);
                stvPay.setVisibility(View.GONE);
            } else if (dataBean.getStatusInt() == 1) {
                tvPayTag.setText("实付：");
                stvPay.setVisibility(View.GONE);
                stvDelete.setVisibility(View.GONE);
                llPayTime.setVisibility(View.VISIBLE);
                llPayWkTIme.setVisibility(View.VISIBLE);
            }else if (dataBean.getStatusInt() == 0) {
                tvPayTag.setText("应付：");
            }
            stvDelete.setOnTextViewClickListener(new SuperTextView.OnTextViewClickListener() {
                @Override
                public void onClick(View v) {
                    CarCommon carCommon = new CarCommon();
                    carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                        @Override
                        public void setSure() {
                            deleteOrder(dataBean.getId());
                        }
                    });
                    carCommon.CommonDialog(OrderDetailActivity.this,"确定要删除该订单吗",null);

                }
            });
            stvCall.setOnTextViewClickListener(new SuperTextView.OnTextViewClickListener() {
                @Override
                public void onClick(View v) {
                    CarCommon carCommon = new CarCommon();
                    carCommon.phoneDialog(OrderDetailActivity.this);
                }
            });
            stvPay.setOnTextViewClickListener(new SuperTextView.OnTextViewClickListener() {
                @Override
                public void onClick(View v) {
                    orderIntentBean.setId(dataBean.getId()+"");
                    orderIntentBean.setDealPrice(dataBean.getDealPrice());
                    orderIntentBean.setParkingId(dataBean.getParkingId());
                    orderIntentBean.setAdvanceMoney(dataBean.getAdvanceMoney());
                    orderIntentBean.setDealUserName(dataBean.getDealUserName());
                    orderIntentBean.setDealPhone(dataBean.getDealPhone());
                    orderIntentBean.setType(dataBean.getPayType());
                    startActivity(new Intent(OrderDetailActivity.this,OrderRetentionMoneyActivity.class)
                            .putExtra("order_bean",orderIntentBean));
                }
            });
            stvStages.setOnTextViewClickListener(new SuperTextView.OnTextViewClickListener() {
                @Override
                public void onClick(View v) {
                    if (dataBean.getIsByStage() == 0) {
                        if (dataBean.getDealPrice() != 0) {
                            orderIntentBean.setId(dataBean.getId() + "");
                            orderIntentBean.setDealPrice(dataBean.getDealPrice());
                            orderIntentBean.setParkingId(dataBean.getParkingId());
                            orderIntentBean.setAdvanceMoney(dataBean.getAdvanceMoney());
                            orderIntentBean.setDealUserName(dataBean.getDealUserName());
                            orderIntentBean.setDealPhone(dataBean.getDealPhone());
                            orderIntentBean.setStatusInt(dataBean.getStatusInt());
                            startActivity(new Intent(OrderDetailActivity.this, ByStagesDetailsActivity.class)
                                    .putExtra("enter_stages_from", 2)
                                    .putExtra("order_mode", orderIntentBean));
                        } else {
                            ToastUtils.showShort("此车位不支持分期");
                        }
                    } else {
                        //分期过
                        orderIntentBean.setId(dataBean.getId()+"");
                        orderIntentBean.setDealPrice(dataBean.getDealPrice());
                        orderIntentBean.setParkingId(dataBean.getParkingId());
                        orderIntentBean.setId(dataBean.getId() + "");
                        orderIntentBean.setDealPrice(dataBean.getDealPrice());
                        orderIntentBean.setParkingId(dataBean.getParkingId());
                        orderIntentBean.setAdvanceMoney(dataBean.getAdvanceMoney());
                        orderIntentBean.setDealUserName(dataBean.getDealUserName());
                        orderIntentBean.setDealPhone(dataBean.getDealPhone());
                        orderIntentBean.setStatusInt(dataBean.getStatusInt());
                        startActivity(new Intent(OrderDetailActivity.this,StagesStepActivity.class)
                                .putExtra("order_mode",orderIntentBean));
                    }
                }
            });
            if (dataBean.getProtocolPhotoUrl() != null && dataBean.getProtocolPhotoUrl().size() > 0) {
                stvHeTong.setVisibility(View.VISIBLE);
                photolist.clear();
                for (int i = 0; i < dataBean.getProtocolPhotoUrl().size(); i++) {
                    photolist.add(dataBean.getProtocolPhotoUrl().get(i).getPhotoUrl());
                }
            }
            stvHeTong.setOnTextViewClickListener(new SuperTextView.OnTextViewClickListener() {
                @Override
                public void onClick(View v) {

                    PhotoViewerBean photoViewerBean = new PhotoViewerBean(photolist, 0);
                    startActivity(new Intent(OrderDetailActivity.this,
                            PhotoViewerActivity.class)
                            .putExtra(PhotoViewerActivity.PHOTO_VIEWER_TAG, photoViewerBean));
                }
            });
            llTop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(OrderDetailActivity.this, StallDealDetailActivity.class);
                    intent.putExtra("stall_id", dataBean.getSpaceId());
                    startActivity(intent);
                }
            });

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }
}
